﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Data;
using Newtonsoft.Json;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Media;
using System.IO;
using System.Net;
using System.Configuration;
using System.Net.Sockets;
using ET.DBCommon;
//using ReportControlLibrary;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// Examination.xaml 的交互逻辑
    /// </summary>
    public partial class Examination : UserControl, INotifyPropertyChanged
    {
        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        #endregion

        public Examination()
        {
            InitializeComponent();
            this.DataContext = this;
            titleCom.Foreground = new SolidColorBrush(Color.FromRgb(255,255,255));


        }
        string revstr;
        int revlength;
        int mbranch = 0;//试卷分支
        EndPoint point;
        EndPoint ipany;
        private Socket _udpRecivesock;//20220815udp接收
        int MyExamResultId = 0;//Add by lukun

        private static object _ExamStateLock = new object();
        #region HisMode
        private bool m_HisMode;

        public bool HisMode
        {
            get
            {
                return this.m_HisMode;
            }
            set
            {
                this.m_HisMode = value;
                this.OnPropertyChanged();
            }
        }
        #endregion



        private ExamResultsModel m_titleExamResultsModel = new ExamResultsModel();
        public ExamResultsModel titleExamResultsModel
        {
            get { return this.m_titleExamResultsModel; }
            set
            {
                this.m_titleExamResultsModel = value;
                this.OnPropertyChanged();
            }
        }
        public void StartExam()
        {
            Task.Run(new Action(() =>
            {
                try
                {
                    //AccountServiceHelper.Instance.SetCurrentTestPaper(this.ExamResultsModel.UserID, this.ExamResultsModel.ID);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("开始评测出错:{SetCurrentTestPaper}");
                  //  EnvironmentContext.Logger.Error(ex.ToString());
                    return;
                }
            }));
        }

        public static List<int> list;

        Task MyExamTask = null;

        CancellationTokenSource MyTakenCancel=new CancellationTokenSource();
        private void UpdateExamResult()
        {
            list = new List<int>();
            list.Clear();
            this.UpdateExamState(true);
            if (MyExamTask != null)
                MyTakenCancel.Cancel();
            Thread.Sleep(1000);
            MyTakenCancel = new CancellationTokenSource();
            MyExamTask = Task.Factory.StartNew(UpdateExamTask, MyTakenCancel.Token);
        }

        private void UpdateExamTask()
        {
            ListenToStepChange stepChange = new ListenToStepChange();
            stepChange.OnStepChanged += Change_OnStepChanged;
            while (!MyTakenCancel.IsCancellationRequested)
            {
                try
                {
                    if (!MainWindowNew.CurMainWindow.ExamState)
                        break;
                    //this.ExamResultsModel = AccountServiceHelper.Instance.GetCurrentExamResult();
                    //if (ExamResultsModel == null)
                    //{
                    //    this.titleExamResultsModel = ExamResultsModel;
                    //}
                    //if (AccountServiceHelper.Instance.UpdateTestPaper())
                    //{
                    //    this.ExamResultsModel = AccountServiceHelper.Instance.GetCurrentExamResult();
                    //    this.titleExamResultsModel = ExamResultsModel;
                    //    this.Dispatcher.Invoke(new Action(() =>
                    //    {
                    //        //重新加载试卷 modify by gy
                    //        this.UpdateLayOut(mainlayOut, true);
                    //        this.UpdateLayOut(fmainlayOut, false);
                    //    }));
                    //    AccountServiceHelper.Instance.SetUpdateTestPaper();
                    //}
                }
                catch (Exception ex)
                {
                   // EnvironmentContext.Logger.Error(ex.ToString());
                    continue;
                }
                if (this.ExamResultsModel != null && this.ExamResultsModel.ID > 0)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        if (this.titleExamResultsModel.Describe == null)
                        {
                            this.titleExamResultsModel = ExamResultsModel;
                        }

                        if (this.mainlayOut.Children.Count == 0)
                        {
                            this.UpdateLayOut(mainlayOut, true);
                        }
                        if (this.fmainlayOut.Children.Count == 0)
                        {
                            this.UpdateLayOut(fmainlayOut, false); //modify by gy
                        }
                        if (this.ExamResultsModel.IsComplete)
                        {
                            this.spButton.Visibility = Visibility.Visible;
                            this.UpdateExamState(false);
                        }
                    }));
                }
                else
                {
                    this.UpdateExamState(false);
                    this.Dispatcher.Invoke(new Action(() => { this.ClearLayOut(mainlayOut); this.ClearLayOut(fmainlayOut); }));
                }


                try
                {

                    //this.Dispatcher.Invoke(new Action(() =>
                    //{
                    //    //找到当前执行中的步骤 Add by gy
                    //    string taskname = null;
                    //    List<TextBlock> mtbkList = FindChirldHelper.FindVisualChild<TextBlock>(mainlayOut);
                    //    List<TextBlock> ftbkList = FindChirldHelper.FindVisualChild<TextBlock>(fmainlayOut);
                    //    if (this.ExamResultsModel != null)
                    //    {
                    //        foreach (var questions in this.ExamResultsModel.ExamresultsTestQuestions)
                    //        {
                    //            foreach (var tasks in questions.ExamresultsTestQuestionTasks)
                    //            {
                    //                taskname = tasks.Tooltips;
                    //                foreach (var steps in tasks.ExamresultsTestQuestionTaskStepModels)
                    //                {
                    //                    if (steps.ExecStateName == "已执行" && !list.Contains(steps.ID))
                    //                    {
                    //                        list.Add(steps.ID);
                    //                        Updateexamresultstestquestiontaskstep(steps.ID, steps.Score);
                    //                    }
                    //                    if (steps.ExecStateName == "执行中")
                    //                    {
                    //                        foreach (var tbk in mtbkList)
                    //                        {

                    //                            if (tbk.Text == taskname)
                    //                            {
                    //                                stepChange.Targettbk = tbk;
                    //                                stepChange.TargetViewer = mainScroll;
                    //                                stepChange.StepIndex = mtbkList.IndexOf(tbk);
                    //                            }
                    //                        }
                    //                        foreach (var tbk in ftbkList)
                    //                        {
                    //                            if (tbk.Text == taskname)
                    //                            {
                    //                                stepChange.Targettbk = tbk;
                    //                                stepChange.TargetViewer = fmainScroll;
                    //                                stepChange.StepIndex = ftbkList.IndexOf(tbk);
                    //                            }
                    //                        }
                    //                    }

                    //                }
                    //            }
                    //        }
                    //    }


                    //}));
                }
                catch (Exception ex)
                {
                  //  EnvironmentContext.Logger.Error(ex.ToString());
                }
                Thread.Sleep(1000);
            }
        }

        //考试更新执行状态和分数,查询可以查询出分数和执行状态 add by ljz
        private void Updateexamresultstestquestiontaskstep(int step,decimal score)
        {
            String sql = "Update examresultstestquestiontaskstep  SET `ExecState`='1',OperationScore=" + score + " where ID=" + step;
            DataSet ds1 = DbHelper.ExecuteDataset(sql);
        }
        private void UpdateExamResultOnce(int StepId)
        {
            String sql = "SELECT * FROM examresults where ID=" + StepId;
            DataSet ds1 = DbHelper.ExecuteDataset(sql);
            if (ds1 != null && ds1.Tables.Count > 0)
            {
                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {
                    string TotalScoreDescribe = ds1.Tables[0].Rows[i]["TotalScoreDescribe"].ToString();
                    string TotalScoreDescribe1 = ds1.Tables[0].Rows[i]["TotalScoreDescribe1"].ToString();
                    string PreTotalScoreDescribe = ds1.Tables[0].Rows[i]["PreTotalScoreDescribe"].ToString();
                    int TestPaperID =Convert.ToInt16( ds1.Tables[0].Rows[i]["TestPaperID"]);
                    ExamResultsModel.TotalScoreDescribe = TotalScoreDescribe;
                    ExamResultsModel.TotalScoreDescribe1 = TotalScoreDescribe1;
                    ExamResultsModel.PreTotalScoreDescribe = PreTotalScoreDescribe;
                    ExamResultsModel.TestPaperID = TestPaperID;
                }
            }
                    
        }
        
        //找到主线任务当前执行中的步骤并跳转 Add by gy
        private void Change_OnStepChanged(TextBlock tbk, ScrollViewer viewer)
        {
            if (tbk != null)
            {
                try
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        tbk.BringIntoView();
                        ScrolltoTarget(tbk, viewer);
                    }));
                }
                catch (Exception ex)
                {
                   // EnvironmentContext.Logger.Error(ex.ToString());
                }
            }
        }
        private void UpdateExamState(bool state)
        {
            lock (_ExamStateLock)
            {
                MainWindowNew.CurMainWindow.ExamState = state;
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (!this.HisMode)
                this.UpdateExamResult();
            //StartCompetition();
            //20220815裁判端UDP接收 Add by gy
            string value = ConfigurationManager.AppSettings["CompetitionDbConnStr"];
            string[] ip = value.Split(';');
            IPAddress ReciveIP = IPAddress.Parse(ip[0].Replace("Server=", ""));//接收消息的IP地址
            string RecivePort = "30303";//接收消息的端口
            IPEndPoint Reciveip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(RecivePort));//网络终结点的IP地址和端口号
            _udpRecivesock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _udpRecivesock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);//端口复用
            _udpRecivesock.Bind(Reciveip);
            byte[] buffer = new byte[1000];
            point = new IPEndPoint(IPAddress.Any, 0);
            ipany = (EndPoint)point;
            //Task.Run(new Action(() => { UdpReceive(); }));
            Task.Run(new Action(() =>
            {
            while (true)
            {
                try
                {

                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (this.mainlayOut.Children.Count > 0)
                        {
                            for (int i = 0; i < mainlayOut.Children.Count; i++)
                            {
                                if (mainlayOut.Children[i].GetType().ToString() == "System.Windows.Controls.TextBlock"&&!MainWindowNew.MissionChecked)
                                {
                                    if (
                                    (mainlayOut.Children[i].GetType().GetProperty("Text").GetValue(mainlayOut.Children[i], null).ToString() == "调度电话_响铃") ||
                                    (mainlayOut.Children[i].GetType().GetProperty("Text").GetValue(mainlayOut.Children[i], null).ToString() == "调度电话_呼入") ||
                                    (mainlayOut.Children[i].GetType().GetProperty("Text").GetValue(mainlayOut.Children[i], null).ToString() == "无线电台_响铃") ||
                                    (mainlayOut.Children[i].GetType().GetProperty("Text").GetValue(mainlayOut.Children[i], null).ToString() == "无线电台_呼入")||
                                    mainlayOut.Children[i].GetType().GetProperty("Name").GetValue(mainlayOut.Children[i], null).ToString() == "fangzhen")
                                    {

                                        mainlayOut.Children[i].Visibility = Visibility.Hidden;
                                        //for(int n = 0; n < 5; n++)
                                        //{
                                        //    if (i + n < mainlayOut.Children.Count - 1)
                                        //    {
                                        //        if (mainlayOut.Children[i + n].GetType().ToString() == "System.Windows.Controls.TextBlock")
                                        //        {
                                        //            mainlayOut.Children[i + n].Visibility = Visibility.Hidden;
                                        //        }
                                        //        else
                                        //        {
                                        //            break;
                                        //        }
                                        //    }
                                        //}
                                       
                                        
                                    }


                                    //this.mainlayOut.Visibility = Visibility.Hidden;
                                }
                                else
                                {
                                    mainlayOut.Children[i].Visibility = Visibility.Visible;
                                }
                            }
                        }
                        if (this.fmainlayOut.Children.Count > 0)
                        {
                            for (int i = 0; i < fmainlayOut.Children.Count; i++)
                            {
                                if (fmainlayOut.Children[i].GetType().ToString() == "System.Windows.Controls.TextBlock" && !MainWindowNew.MissionChecked)
                                {
                                    if
                                    (
                                    (fmainlayOut.Children[i].GetType().GetProperty("Text").GetValue(fmainlayOut.Children[i], null).ToString() == "调度电话_响铃") ||
                                    (fmainlayOut.Children[i].GetType().GetProperty("Text").GetValue(fmainlayOut.Children[i], null).ToString() == "调度电话_呼入") ||
                                    (fmainlayOut.Children[i].GetType().GetProperty("Text").GetValue(fmainlayOut.Children[i], null).ToString() == "无线电台_响铃") ||
                                    (fmainlayOut.Children[i].GetType().GetProperty("Text").GetValue(fmainlayOut.Children[i], null).ToString() == "无线电台_呼入") ||
                                     fmainlayOut.Children[i].GetType().GetProperty("Name").GetValue(fmainlayOut.Children[i], null).ToString()== "fangzhen")
                                        
                                    {

                                        fmainlayOut.Children[i].Visibility = Visibility.Hidden;
                                        //for (int n = 0; n < 5; n++)
                                        //{
                                        //    if (i + n < fmainlayOut.Children.Count - 1)
                                        //    {
                                        //        if (fmainlayOut.Children[i + n].GetType().ToString() == "System.Windows.Controls.TextBlock"
                                        //        {
                                        //            fmainlayOut.Children[i + n].Visibility = Visibility.Hidden;
                                        //        }
                                        //        else
                                        //        {
                                        //            break;
                                        //        }
                                        //    }
                                        //}


                                        //this.mainlayOut.Visibility = Visibility.Hidden;
                                    }
                                }
                                else
                                {
                                    fmainlayOut.Children[i].Visibility = Visibility.Visible;
                                }
                            }
                        }
                       
                        }));
                    }
                    catch (Exception ex)
                    {
                       
                    }

                   

                    Thread.Sleep(1000);
                }
            }));




        }
        private void UdpReceive()//裁判端UDP接收
        {
            while (true)
            {
                int index = 0;
                byte[] buffer = new byte[1000];
                _udpRecivesock.ReceiveFrom(buffer, ref ipany);
                if (buffer[0] == 0xA7)
                {
                    index += 1;
                    revlength = BitConverter.ToInt16(buffer, 1);
                    index += 2;
                    index += 2;
                    revstr = Encoding.UTF8.GetString(buffer, index, revlength);

                    if (revstr.Contains("失表，无定位，无反位"))
                    {
                        mbranch = 1;
                    }
                    else if (revstr.Contains("有定位，无反位，需要现场确认"))
                    {
                        mbranch = 2;
                    }
                    else if (revstr.Contains("有反位，无定位"))
                    {
                        mbranch = 3;
                    }

                }
                Thread.Sleep(1000);
            }
        }

       
        /// <summary>
        /// 开始比赛
        /// </summary>
        /// <param name="examResultsModel"></param>
        public void StartCompetition(ExamResultsModel examResultsModel = null)
        {
            //MyExamResultId = 0;
            //this.mbranch = 0;
            ////AccountServiceHelper.Instance.ClearCurrentExam();
            //if (examResultsModel != null)
            //{
            //   var loadid1 = this.Dispatcher.InvokeAsync(new Action(() =>
            //    {
            //        MyExamResultId = ExamResultsDAL.InsertExamResults(examResultsModel);
            //    }));
            //   loadid1.Completed += new EventHandler(Loadid_Completed);
            //}
            //if (examResultsModel == null && !MainWindowNew.CurMainWindow.ExamState)
            //{
            //    //异步处理获取examresult Add by gy
            //    var loadid = this.Dispatcher.InvokeAsync(new Action(() =>
            //    {
            //        MyExamResultId = ExamResultsDAL.InsertExamResults(new ExamResultsModel() { TestPaperID = MainWindowNew.ChooseTestPaper.Id, UserID = MainWindowNew.ChooseUser.Id });
            //    }));
            //    loadid.Completed += new EventHandler(Loadid_Completed);
        
            //}
        }
        private void Loadid_Completed(object sender, EventArgs e)
        {
            if (MyExamResultId > 0)
            {
                this.ExamResultsModel = null;
                this.titleExamResultsModel = null;
                this.spButton.Visibility = Visibility.Collapsed;
                //MyExamResultId = examResultId;
               var loadmodel = this.Dispatcher.InvokeAsync(new Action(() =>
                {
                    this.ExamResultsModel = ExamResultsDAL.GetExamResultById(MyExamResultId);
                    this.titleExamResultsModel = this.ExamResultsModel;
                   //titleCom.ItemsSource = this.ExamResultsModel.ExamresultsTestQuestions;

                }));
                loadmodel.Completed += new EventHandler(Loadmodel_Completed);

            }
        }
        private void Loadmodel_Completed(object sender, EventArgs e)
        {
            if (this.ExamResultsModel != null)
            {
                this.Dispatcher.Invoke(new Action(() => {
                    this.ClearLayOut(mainlayOut); this.ClearLayOut(fmainlayOut); SumGrid.RowDefinitions.Clear();
                    SumGrid.ColumnDefinitions.Clear();
                    SumGrid.Children.Clear();
                }));
                //this.ExamResultsModel = ExamResultsDAL.GetExamResultById(62, true);
                this.UpdateLayOut(mainlayOut, true);
                this.UpdateLayOut(fmainlayOut, false);//主线任务窗口 modify by gy
                this.StartExam();
                this.UpdateExamResult();
            }
        }



        private void ClearLayOut(Grid layOut)
        {
            layOut.RowDefinitions.Clear();
            layOut.ColumnDefinitions.Clear();
            layOut.Children.Clear();
        }
        private static System.ComponentModel.DependencyPropertyDescriptor descriptor1 = System.ComponentModel.DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
        private void UpdateLayOut(Grid layOut, bool IsMain)
        {
            if (this.ExamResultsModel.ID > 0)
            {
                this.ClearLayOut(layOut);
                //单独清理SumGrid Add by gy
                if (IsMain)
                {
                    SumGrid.RowDefinitions.Clear();
                    SumGrid.ColumnDefinitions.Clear();
                    SumGrid.Children.Clear();
                }
                layOut.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(10, GridUnitType.Pixel) });
                layOut.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                layOut.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                layOut.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                if (ExamResultsModel.ExamresultsTestQuestions.Count>1)
                {
                    this.Dispatcher.Invoke(new Action(() => {
                        int title = titleCom.SelectedIndex;
                        if (title < 0)
                        {
                            title = 0;
                            titleCom.SelectedIndex = 0;
                        }

                        this.AddQuestionArea(ExamResultsModel.ExamresultsTestQuestions[title], layOut, IsMain);
                    }));
                }
                else
                {
                    for (int i = 0; i < ExamResultsModel.ExamresultsTestQuestions.Count; i++)
                    {
                        this.AddQuestionArea(ExamResultsModel.ExamresultsTestQuestions[i], layOut, IsMain);
                    }
                }
                

                if (IsMain)//成绩汇总在SumGrid中生成 modify by gy
                {
                    SumGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(20, 0, 0, 0) };
                    TextBlock txtTitle = new TextBlock() { Text = "总成绩：", Margin = new Thickness(10, 0, 10, 0) };
                    sp.Children.Add(txtTitle);
                    //总成绩显示修改为文字性描述 add by ljz 2023/9/20
                    TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, TextAlignment = TextAlignment.Center };
                    TextBlock txtValue2 = new TextBlock() { Foreground = Brushes.Red, TextAlignment = TextAlignment.Center };
                    TextBlock txtValue1 = new TextBlock() { Foreground = new SolidColorBrush(Color.FromRgb(77, 244, 13)), TextAlignment = TextAlignment.Center, Margin = new Thickness(-470,0,0,0)};
                    TextBlock txtValue3 = new TextBlock() { Foreground = new SolidColorBrush(Color.FromRgb(77, 244, 13)), TextAlignment = TextAlignment.Center, Margin = new Thickness(-325,0,0,0)};
                    UpdateExamResultOnce(this.ExamResultsModel.ID);
                    var testpaperLevel = ExamResultsDAL.getLevel(this.ExamResultsModel.TestPaperID);
                    if (titleCom.Text.Contains("运行前"))
                    {
                        txtValue2.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.PreTotalScoreDescribe"));
                        sp.Children.Add(txtValue2);
                    }
                    else if (testpaperLevel=="5")
                    {
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.TotalScoreDescribe"));
                        txtValue3.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.TotalScoreDescribe1"));
                        sp.Children.Add(txtValue);
                        sp.Children.Add(txtValue3);
                    }
                    else
                    {
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.TotalScoreDescribe"));
                        txtValue1.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.TotalScoreDescribe1"));
                        sp.Children.Add(txtValue);
                        sp.Children.Add(txtValue1);
                    }
                    
                    
                    
                   
                  
                    
                    //descriptor1.AddValueChanged(txtValue, TbTextChanged1);
                    sp.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count);
                    sp.SetValue(Grid.ColumnProperty, 1);
                    sp.SetValue(Grid.ColumnSpanProperty, layOut.ColumnDefinitions.Count - 1);
                    SumGrid.Children.Add(sp);
                    ButtonCloseSum.Visibility = Visibility.Visible;
                }
            }
            //layOut.DataContext = this.ExamResultsModel;          
        }

        private void AddQuestionArea(ExamresultsTestQuestionModel question, Grid layOut, bool IsMain)
        {
            layOut.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            TextBlock textDes = new TextBlock() { Text = question.Name, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 10, 5, 10), TextWrapping = TextWrapping.WrapWithOverflow };
            textDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            textDes.SetValue(Grid.ColumnProperty, 1);
            textDes.SetValue(Grid.ColumnSpanProperty, 3);
            layOut.Children.Add(textDes);
            this.AddTasksArea(question, false, "任务列表", layOut, IsMain);
            if (IsMain)
            {
                layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20, GridUnitType.Pixel) });
                this.AddSummationArea(question, SumGrid);
            }
            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20, GridUnitType.Pixel) });
        }

        private void AddTasksArea(ExamresultsTestQuestionModel question, bool isOther, string titel, Grid layOut, bool IsMain)
        {
            var taskList = question.ExamresultsTestQuestionTasks.ToList().FindAll(p => p.UIOrder < 200 && p.IsMain == IsMain && p.ExamresultsTestQuestionTaskStepModels.Count != p.ExamresultsTestQuestionTaskStepModels.Count(x => x.TaskType == (int)TaskType.仿真 && x.SystemType == (int)SystemType.ATS));
            var temptasklist = question.ExamresultsTestQuestionTasks.ToList().FindAll(p => p.UIOrder < 200 && p.IsMain == IsMain && p.ExamresultsTestQuestionTaskStepModels.Count != p.ExamresultsTestQuestionTaskStepModels.Count(x => x.TaskType == (int)TaskType.仿真 && x.SystemType == (int)SystemType.ATS));
            int stepCount = 0;
            taskList.ForEach(p =>
            {
                stepCount += p.ExamresultsTestQuestionTaskStepModels.Where(x => x.TaskType == (int)TaskType.仿真 && x.SystemType != (int)SystemType.ATS).Count();
                stepCount += p.ExamresultsTestQuestionTaskStepModels.Where(x => x.TaskType == (int)TaskType.任务).Count() * 3;
            });
            if (taskList.Count() > 0)
            {
                titel = IsMain ? "主线任务列表" : "非主线任务列表";//Add by gy
                int questionIndex = this.ExamResultsModel.ExamresultsTestQuestions.IndexOf(question);
                this.CreateAreaHeader(taskList.Count() + stepCount + 1, titel, layOut);


                if (mbranch == 1)
                {
                    var temp = temptasklist.Where(T => T.Branch.Contains("1") && T.IsMain == IsMain).ToList();
                    for (int j = 0; j < temp.Count(); j++)
                    {
                        this.AddTaskArea(temp[j], questionIndex, question.ExamresultsTestQuestionTasks.IndexOf(temp[j]), layOut);
                    }
                }
                else if (mbranch == 2)
                {
                    var temp = temptasklist.Where(T => T.Branch.Contains("2") && T.IsMain == IsMain).ToList();
                    for (int j = 0; j < temp.Count(); j++)
                    {
                        this.AddTaskArea(temp[j], questionIndex, question.ExamresultsTestQuestionTasks.IndexOf(temp[j]), layOut);
                    }
                }
                else if (mbranch == 3)
                {
                    var temp = temptasklist.Where(T => T.Branch.Contains("3") && T.IsMain == IsMain).ToList();
                    for (int j = 0; j < temp.Count(); j++)
                    {
                        this.AddTaskArea(temp[j], questionIndex, question.ExamresultsTestQuestionTasks.IndexOf(temp[j]), layOut);
                    }
                }
                else
                {
                    for (int j = 0; j < taskList.Count(); j++)
                    {
                        this.AddTaskArea(taskList[j], questionIndex, question.ExamresultsTestQuestionTasks.IndexOf(taskList[j]), layOut);
                    }
                }


            }
        }

        private void AddTaskArea(ExamresultsTestQuestionTaskModel task, int questionIndex, int taskIndex, Grid layOut)
        {
            StackPanel spTask = new StackPanel() { Orientation = Orientation.Horizontal };
            //TextBlock textTaskDes = new TextBlock() { Text = task.Tooltips, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = task.IsMain ? Brushes.Red : (task.UIOrder > 100 ? Brushes.SlateBlue : Brushes.Goldenrod), Margin = new Thickness(5) };
            Button textTaskDes = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Content = task.Tooltips, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = task.IsMain ? new SolidColorBrush(Color.FromRgb(255, 51, 51)) : (task.UIOrder > 200 ? Brushes.SlateBlue : Brushes.Goldenrod), Margin = new Thickness(5) };
            Button taskSkip = new Button() { Tag = task.ID, Style = this.FindResource("LinkButton") as System.Windows.Style, Content = "强制跳过", VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(0, 140, 234)), Margin = new Thickness(5) };
            taskSkip.SetBinding(VisibilityProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].Status", questionIndex, taskIndex)) { Converter = this.FindResource("StatusVisibleConverter") as IValueConverter });
            taskSkip.Click += TaskSkip_Click;
            spTask.Children.Add(textTaskDes);
            spTask.Children.Add(taskSkip);
            spTask.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count);
            spTask.SetValue(Grid.ColumnProperty, 1);
            spTask.SetValue(Grid.ColumnSpanProperty, 3);
            layOut.Children.Add(spTask);

            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40, GridUnitType.Pixel) });

            foreach (var step in task.ExamresultsTestQuestionTaskStepModels)
            {
                if (step.TaskType == (int)TaskType.仿真 && step.SystemType == (int)SystemType.ATS) continue;

                this.AddStepArea(step, questionIndex, taskIndex, task.ExamresultsTestQuestionTaskStepModels.IndexOf(step), layOut);
            

        }
        }
        //public static bool Start=true;
        private void TaskSkip_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            if (btn.Tag == null) return;
            if (MessageBox.Show("是否跳过任务？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                //AccountServiceHelper.Instance.MainTaskSkip(int.Parse(btn.Tag.ToString()));
            }
        }
        private static System.ComponentModel.DependencyPropertyDescriptor descriptor =System.ComponentModel.DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
        private void AddStepArea(ExamresultsTestQuestionTaskStepModel step, int questionIndex, int taskIndex, int stepIndex, Grid layOut)
        {

            //this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
            //layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50, GridUnitType.Pixel) });
            //StackPanel textsp = new StackPanel() { Orientation = Orientation.Vertical,CanHorizontallyScroll=true,Width=500};
            //textsp.Background = new SolidColorBrush(step.TaskType == (int)TaskType.仿真 ? Color.FromRgb(50, 126, 200) : Color.FromRgb(45, 59, 72));
            //textsp.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            //textsp.SetValue(Grid.ColumnProperty, 1);
            //textsp.SetValue(Grid.ColumnSpanProperty, 4);
            //TextBlock textStep = new TextBlock() { Text = ((StepItemEnum)step.StepID).ToString(), VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, Margin = new Thickness(5, 0, 20, 0), TextWrapping = TextWrapping.Wrap };

            //TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe/*.Substring(0, 41)*/, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5, 0, 20, 0), TextWrapping = TextWrapping.Wrap, Padding = new Thickness(5) };

            //textsp.Children.Add(textStep);
            //textsp.Children.Add(textStepDes);

            //layOut.Children.Add(textsp);

            if (step.StepDescribe?.Length <= 41)
            {
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStep = new TextBlock() { Text = ((StepItemEnum)step.StepID).ToString(), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 0, 20, 0) };
                textStep.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStep.SetValue(Grid.ColumnProperty, 1);
                layOut.Children.Add(textStep);
                if (step.TaskType == (int)TaskType.仿真)
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(254, 254, 254)), Margin = new Thickness(5), Name = "fangzhen" };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes);
                }
                else
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes);
                }

            }

            //两行换行
            else if (step.StepDescribe?.Length > 41 && step.StepDescribe?.Length <= 82)
            {
                //layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(60, GridUnitType.Pixel) });

                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStep = new TextBlock() { Text = ((StepItemEnum)step.StepID).ToString(), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 0, 20, 0) };
                textStep.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStep.SetValue(Grid.ColumnProperty, 1);
                layOut.Children.Add(textStep);
                if (step.TaskType == (int)TaskType.仿真)
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe.Substring(0, 41), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Stretch, Foreground = new SolidColorBrush(Color.FromRgb(254, 254, 254)), Margin = new Thickness(5), Name = "fangzhen"/*TextWrapping = TextWrapping.WrapWithOverflow,*/ /*Padding = new Thickness(5)*/ };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    //textStepDes.ToolTip = step.StepDescribe.ToString();
                    //textStepDes.Background = new SolidColorBrush(step.TaskType == (int)TaskType.仿真 ? Color.FromRgb(50, 126, 200) : Color.FromRgb(45, 59, 72));
                    layOut.Children.Add(textStepDes);

                    var StepDescribe2 = step.StepDescribe.Substring(41);
                    this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                    TextBlock textStepDes2 = new TextBlock() { Text = StepDescribe2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(254, 254, 254)), Margin = new Thickness(5), Name = "fangzhen" };
                    textStepDes2.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes2.SetValue(Grid.ColumnProperty, 2);
                    textStepDes2.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes2);
                }
                else
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe.Substring(0, 41), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Stretch, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5), /*TextWrapping = TextWrapping.WrapWithOverflow,*/ /*Padding = new Thickness(5)*/ };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    //textStepDes.ToolTip = step.StepDescribe.ToString();
                    //textStepDes.Background = new SolidColorBrush(step.TaskType == (int)TaskType.仿真 ? Color.FromRgb(50, 126, 200) : Color.FromRgb(45, 59, 72));
                    layOut.Children.Add(textStepDes);

                    var StepDescribe2 = step.StepDescribe.Substring(41);
                    this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                    TextBlock textStepDes2 = new TextBlock() { Text = StepDescribe2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                    textStepDes2.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes2.SetValue(Grid.ColumnProperty, 2);
                    textStepDes2.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes2);
                }

            }

            //三行换行
            else if (step.StepDescribe?.Length > 82 && step.StepDescribe?.Length <= 123)
            {
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStep = new TextBlock() { Text = ((StepItemEnum)step.StepID).ToString(), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 0, 20, 0) };
                textStep.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStep.SetValue(Grid.ColumnProperty, 1);
                layOut.Children.Add(textStep);

                if (step.TaskType == (int)TaskType.仿真)
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe.Substring(0, 41), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) ,Name = "fangzhen" };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes);


                    var StepDescribe2 = step.StepDescribe.Substring(41, 41);
                    this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                    TextBlock textStepDes2 = new TextBlock() { Text = StepDescribe2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) , Name = "fangzhen" };
                    textStepDes2.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes2.SetValue(Grid.ColumnProperty, 2);
                    textStepDes2.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes2);

                    var StepDescribe3 = step.StepDescribe.Substring(82);
                    this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                    TextBlock textStepDes3 = new TextBlock() { Text = StepDescribe3, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5), Name = "fangzhen" };
                    textStepDes3.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes3.SetValue(Grid.ColumnProperty, 2);
                    textStepDes3.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes3);

                }
                else
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe.Substring(0, 41), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes);


                    var StepDescribe2 = step.StepDescribe.Substring(41, 41);
                    this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                    TextBlock textStepDes2 = new TextBlock() { Text = StepDescribe2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                    textStepDes2.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes2.SetValue(Grid.ColumnProperty, 2);
                    textStepDes2.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes2);

                    var StepDescribe3 = step.StepDescribe.Substring(82);
                    this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                    TextBlock textStepDes3 = new TextBlock() { Text = StepDescribe3, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                    textStepDes3.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes3.SetValue(Grid.ColumnProperty, 2);
                    textStepDes3.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes3);
                }
            }
            //四行换行
            else if (step.StepDescribe?.Length > 123)
            {
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStep = new TextBlock() { Text = ((StepItemEnum)step.StepID).ToString(), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 0, 20, 0) };
                textStep.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStep.SetValue(Grid.ColumnProperty, 1);
                layOut.Children.Add(textStep);

                TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe.Substring(0, 41), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStepDes.SetValue(Grid.ColumnProperty, 2);
                textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                layOut.Children.Add(textStepDes);


                var StepDescribe2 = step.StepDescribe.Substring(41, 41);
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStepDes2 = new TextBlock() { Text = StepDescribe2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                textStepDes2.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStepDes2.SetValue(Grid.ColumnProperty, 2);
                textStepDes2.SetValue(Grid.ColumnSpanProperty, 3);
                layOut.Children.Add(textStepDes2);

                var StepDescribe3 = step.StepDescribe.Substring(82, 41);
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStepDes3 = new TextBlock() { Text = StepDescribe3, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                textStepDes3.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStepDes3.SetValue(Grid.ColumnProperty, 2);
                textStepDes3.SetValue(Grid.ColumnSpanProperty, 3);
                layOut.Children.Add(textStepDes3);

                var StepDescribe4 = step.StepDescribe.Substring(123);
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStepDes4 = new TextBlock() { Text = StepDescribe4, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                textStepDes4.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStepDes4.SetValue(Grid.ColumnProperty, 2);
                textStepDes4.SetValue(Grid.ColumnSpanProperty, 3);
                layOut.Children.Add(textStepDes4);
            }
            else
            {
                this.CreateGray(layOut, step.TaskType == (int)TaskType.仿真);
                TextBlock textStep = new TextBlock() { Text = ((StepItemEnum)step.StepID).ToString(), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 0, 20, 0), TextWrapping = TextWrapping.Wrap };


                textStep.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                textStep.SetValue(Grid.ColumnProperty, 1);
                layOut.Children.Add(textStep);
                //if (step.TaskType == (int)TaskType.仿真)
                //{
                //    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(254, 254, 254)), Margin = new Thickness(5) };
                //    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                //    textStepDes.SetValue(Grid.ColumnProperty, 2);
                //    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                //    layOut.Children.Add(textStepDes);
                //}
                //else
                {
                    TextBlock textStepDes = new TextBlock() { Text = step.StepDescribe, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = new SolidColorBrush(Color.FromRgb(251, 251, 251)), Margin = new Thickness(5) };
                    textStepDes.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                    textStepDes.SetValue(Grid.ColumnProperty, 2);
                    textStepDes.SetValue(Grid.ColumnSpanProperty, 3);
                    layOut.Children.Add(textStepDes);
                }


            }



            if (step.TaskType == (int)TaskType.仿真) return;
            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40, GridUnitType.Pixel) });

            StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(5) };
            TextBlock textStepStateInfo = new TextBlock() { Text = "执行状态：", VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Width = 75 };
            TextBlock textStepState = new TextBlock() { Foreground = Brushes.FloralWhite,Width = 60, VerticalAlignment = VerticalAlignment.Center};
            
            TextBlock textTimeScoreInfo = new TextBlock() { Text = "得分: ", Width = 40, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right };
            TextBlock textTimeScore = new TextBlock() { Foreground = Brushes.FloralWhite, Width = 120, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Left };
            TextBlock textSubjectiveScore = new TextBlock() { Text = "主观分: ", VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Width = 75 };
            TextBox txtZGScore = new TextBox() { Style = FindResource("ScoreStyle") as System.Windows.Style, VerticalAlignment = VerticalAlignment.Center };

            Button btnAudio = new Button() { Margin = new Thickness(10, 0, 0, 0), Style = this.FindResource("PlayAudioButton") as System.Windows.Style };
            Button btnRight = new Button() { Width = 87, Content = "正确跳过", Margin = new Thickness(10, 0, 5, 0) };
            Button btnError = new Button() { Width = 87, Content = "错误跳过", Margin = new Thickness(10, 0, 5, 0) };
            //Button btnLose = new Button() { Width = 88, Content = "关键步骤失分", Margin = new Thickness(10, 0, 5, 0),Visibility=Visibility.Hidden};//20220913关键步骤失分按钮 add by gy 
            //btnLose.Visibility = Visibility.Hidden;
            btnAudio.Click += BtnAudio_Click;
            btnRight.Click += BtnRight_Click;
            btnError.Click += BtnRight_Click;

            textStepState.SetBinding(TextBlock.TextProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ExecStateName", questionIndex, taskIndex, stepIndex)));
            textTimeScore.SetBinding(TextBlock.TextProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].StrOperationScore", questionIndex, taskIndex, stepIndex)));
            txtZGScore.SetBinding(TextBox.TextProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].CompositeScore", questionIndex, taskIndex, stepIndex)));
            btnAudio.SetBinding(TagProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ID", questionIndex, taskIndex, stepIndex)));
            btnRight.SetBinding(TagProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ID", questionIndex, taskIndex, stepIndex)));
            btnError.SetBinding(TagProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ID", questionIndex, taskIndex, stepIndex)));
            //btnLose.SetBinding(TagProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ID", questionIndex, taskIndex, stepIndex)));

            btnRight.SetBinding(VisibilityProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ExecState", questionIndex, taskIndex, stepIndex)) { Converter = this.FindResource("ExecStateToVisibleConverter") as IValueConverter });
            btnError.SetBinding(VisibilityProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ExecState", questionIndex, taskIndex, stepIndex)) { Converter = this.FindResource("ExecStateToVisibleConverter") as IValueConverter });
            //btnLose.SetBinding(VisibilityProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ExecState", questionIndex, taskIndex, stepIndex)) { Converter = this.FindResource("ExecStateToVisibleConverter") as IValueConverter });
            //订阅文字修改 add by ljz
            descriptor.AddValueChanged(textStepState, TbTextChanged);

        sp.Children.Add(textStepStateInfo);
            sp.Children.Add(textStepState);
            sp.Children.Add(textTimeScoreInfo);
            sp.Children.Add(textTimeScore);
            //sp.Children.Add(textSubjectiveScore);
            //sp.Children.Add(txtZGScore);
            if (step.StepID == (int)StepItemEnum.无线电台_呼出 || step.StepID == (int)StepItemEnum.调度电话_呼出)
                sp.Children.Add(btnAudio);
            sp.Children.Add(btnRight);
            sp.Children.Add(btnError);
            //sp.Children.Add(btnLose);

            sp.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            sp.SetValue(Grid.ColumnProperty, 3);
            layOut.Children.Add(sp);

            var row = new RowDefinition();
            row.SetBinding(RowDefinition.HeightProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ScoreDescribe", questionIndex, taskIndex, stepIndex)) { Converter = this.FindResource("TextToHightConverter") as IValueConverter });
            layOut.RowDefinitions.Add(row);
            TextBlock textScoreDescribe = new TextBlock() { Text = step.StepDescribe, FontSize = 12, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Foreground = Brushes.Green, Margin = new Thickness(5) };
            textScoreDescribe.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            textScoreDescribe.SetValue(Grid.ColumnProperty, 2);
            textScoreDescribe.SetValue(Grid.ColumnSpanProperty, 3);

            textScoreDescribe.SetBinding(TextBlock.TextProperty, new Binding(string.Format("ExamResultsModel.ExamresultsTestQuestions[{0}].ExamresultsTestQuestionTasks[{1}].ExamresultsTestQuestionTaskStepModels[{2}].ScoreDescribe", questionIndex, taskIndex, stepIndex)));
            layOut.Children.Add(textScoreDescribe);

        }
        //将已执行修改为绿色 add by ljz
        private static void TbTextChanged(object sender, EventArgs e)
        {
            if (sender.GetType().GetProperty("Text").GetValue(sender, null).ToString()== "已执行")
            {
                sender.GetType().GetProperty("Foreground").SetValue(sender,new SolidColorBrush(Color.FromRgb(77,244,13)));
            }
        }
        private static void TbTextChanged1(object sender, EventArgs e)
        {
            if (sender.GetType().GetProperty("Text").GetValue(sender, null).ToString().Contains("="))
            {
                var count = 0;
                foreach(var txt in sender.GetType().GetProperty("Text").GetValue(sender, null).ToString())
                {
                    if (txt.ToString() == "=")
                    {
                        
                        
                        txt.GetType().GetProperties();
                        
                    }
                    if (count != 0)
                    {
                        
                        sender.GetType().GetProperty("Text").SetValue(sender, txt.ToString());
                        count++;
                        if (count > 5)
                        {
                            count = 0;
                        }
                    }
                    
                }
                
            }
        }
        private void BtnAudio_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            if (btn.Tag != null)
            {
                var audioBuff = ExamresultsTestQuestionTaskStepDAL.GetStepAudioBuff(int.Parse(btn.Tag.ToString()));
                if (audioBuff == null) return;
                Task.Run(() =>
                {
                    MemoryStream ms = new MemoryStream();
                    ms.Write(audioBuff, 0, audioBuff.Length);
                    ms.Position = 0;
                    SoundPlayer player = new SoundPlayer() { Stream = ms };
                    player.Load();
                    player.PlaySync();
                    ms.Close();
                });
            }
        }

        private void BtnRight_Click(object sender, RoutedEventArgs e)
        {
            var btn = e.OriginalSource as Button;
            //if (btn.Content.ToString() == "正确跳过")
            //    AccountServiceHelper.Instance.CorrectSkip(int.Parse(btn.Tag.ToString()));
            //else
            //    AccountServiceHelper.Instance.ErrorSkip(int.Parse(btn.Tag.ToString()));
        }

        private void AddSummationArea(ExamresultsTestQuestionModel question, Grid layOut)
        {
            this.CreateAreaHeader(4, "分数汇总", layOut);
            
            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(45, GridUnitType.Pixel) });
            int questionIndex = this.ExamResultsModel.ExamresultsTestQuestions.IndexOf(question);
            decimal TestperTotal = 0;
            ExamresultsTestQuestionDAL.UpdateExamresultsTestQuestionTestPaperScore(question);
            ExamresultsTestQuestionDAL.SetTestpaperTotal(question, out TestperTotal);
            ExamresultsTestQuestionModel info=ExamresultsTestQuestionDAL.getScentFile(this.ExamResultsModel.ExamresultsTestQuestions[questionIndex].ID);
            //修改裁判显示 add by ljz 20237.25
            this.CreateStackPanelArea(question, new string[] { "停运晚点迫停总分：" }, new string[] { "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].StopLaterScore"}, 1, layOut);
            this.CreateGray(layOut, false);
            this.CreateStackPanelArea(question, new string[] { "    ","停运扣分：", "晚点扣分：", "迫停扣分：" }, new string[] { "","ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].StopsRunningCount", "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].TrainLateCount", "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].TrainSuspendCount" }, 1, layOut);
            //this.CreateStackPanelArea(question, new string[] { "提交元素总分：", "提交元素扣分：" }, new string[] { "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].SubmitElementScore", "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].RecordtimeErrorCount" }, 1, layOut);
            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(45, GridUnitType.Pixel) });
            var testpaperLevel = ExamresultsTestQuestionDAL.getLevel(question.TestQuestionID);
            if (testpaperLevel!="5")
            {
                this.CreateStackPanelArea(question, new string[] { "试卷得分：" }, new string[] { "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].StepScore", }, 1, layOut);
            }
            else
            {
                this.CreateStackPanelArea(question, new string[] { "客流总分：" }, new string[] { "15", }, 1, layOut);
            }
            
            this.CreateGray(layOut, false);

            if (questionIndex == 1&& testpaperLevel != "5")
            {
                this.CreateStackPanelArea1(question, new string[] { "    ", "扣分步骤：", "试卷总分：", "场景总计时：" }, new string[] { "", "查看", TestperTotal.ToString(), "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].TotalTime" }, 1, layOut);
               
            }
            else if (testpaperLevel == "5")
            {
                this.CreateStackPanelArea2(question, new string[] { "    ", "客流扣分：", "试卷总分：", "场景总计时：" }, new string[] { "", "查看", TestperTotal.ToString(), "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].TotalTime" }, 1, layOut);
            }
            else
            {
                this.CreateStackPanelArea(question, new string[] { "    ", "扣分步骤：", "试卷总分：", "场景总计时：" }, new string[] { "", "查看", TestperTotal.ToString(), "ExamResultsModel.ExamresultsTestQuestions[" + questionIndex + "].TotalTime" }, 1, layOut);
            }
           

            

        }

        private void CreateAreaHeader(int rowSpan, string header, Grid layOut)
        {
            layOut.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            System.Windows.Controls.Border CurTaskAreaBorder = new System.Windows.Controls.Border() { BorderBrush = new SolidColorBrush(Color.FromRgb(45, 59, 72)), BorderThickness = new Thickness(1), Margin = new Thickness(0, 0, 1, -1) };
            CurTaskAreaBorder.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            CurTaskAreaBorder.SetValue(Grid.ColumnProperty, 1);
            CurTaskAreaBorder.SetValue(Grid.ColumnSpanProperty, 3);
            CurTaskAreaBorder.SetValue(Grid.RowSpanProperty, rowSpan);
            layOut.Children.Add(CurTaskAreaBorder);

            ToolButton toolButton = new ToolButton() { MenuName = header, Margin = new Thickness(0, 0, 1, 0), Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Top, VerticalContentAlignment = VerticalAlignment.Center, Style = FindResource("TitleStyle1") as System.Windows.Style };
            toolButton.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            toolButton.SetValue(Grid.ColumnProperty, 1);
            toolButton.SetValue(Grid.ColumnSpanProperty, 3);
            layOut.Children.Add(toolButton);
        }

        private void CreateGray(Grid layOut, bool fangzhen = false)
        {
            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(44, GridUnitType.Pixel) });

            Label grid = new Label() /*{ Background = new SolidColorBrush(fangzhen ? Color.FromRgb(198, 239, 206) : Color.FromRgb(232, 233, 238)), Margin = new Thickness(1, 0, 3, 0) }*/;
            //label样式模板 Add by gy
            ControlTemplate gridTemplate = new ControlTemplate(typeof(Label));
            FrameworkElementFactory borderElement = new FrameworkElementFactory(typeof(Border));
            borderElement.SetValue(Border.MarginProperty, new Thickness(1, 0, 3, 0));
            // borderElement.SetValue(Border.BorderThicknessProperty, new Thickness(1));
            // borderElement.SetValue(Border.BorderBrushProperty, new SolidColorBrush(fangzhen ? Color.FromRgb(80, 100, 200): Color.FromRgb(45, 100, 80)));
            borderElement.SetValue(Border.BackgroundProperty, new SolidColorBrush(fangzhen ? Color.FromRgb(4, 36, 119) : Color.FromRgb(45, 59, 72)));
            borderElement.SetValue(Border.CornerRadiusProperty, new CornerRadius(0));
            borderElement.SetValue(MarginProperty, new Thickness(1, 1, 0, 1));
            gridTemplate.VisualTree = borderElement;
            grid.Template = gridTemplate;
            grid.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            grid.SetValue(Grid.ColumnProperty, 1);
            grid.SetValue(Grid.ColumnSpanProperty, 4);
            layOut.Children.Add(grid);

        }

        private void CreateGray(Grid layOut, int colIndex = 0, int colSpan = 10)
        {
            layOut.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40, GridUnitType.Pixel) });

            Label grid = new Label() { Background = new SolidColorBrush(Color.FromRgb(45, 59, 72)), Margin = new Thickness(1, 0, 3, 0) };
            grid.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            grid.SetValue(Grid.ColumnProperty, colIndex);
            grid.SetValue(Grid.ColumnSpanProperty, colSpan);
            layOut.Children.Add(grid);
        }

        private void CreateStackPanelArea(ExamresultsTestQuestionModel question, string[] titles, string[] propertys, int colIndex, Grid layOut)
        {
            StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(20, 0, 0, 0) };
            for (int i = 0; i < titles.Length; i++)
            {
                TextBlock txtTitle = new TextBlock() { Width = 135, Text = titles[i], Margin = new Thickness(10, 0, 10, 0) };
                sp.Children.Add(txtTitle);
                //修改成绩汇总显示 add by ljz 2023.7.25
                if (new string[] { "晚点扣分", "停运扣分", "迫停扣分", "提交元素扣分", "操作得分", "扣分步骤" }.Contains(titles[i].TrimEnd('：')))
                {
                    if (titles[i].Contains("    "))
                    {
                        Button txtValue = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Width = 100 };
                        txtValue.Content ="";
                    }
                    else
                    {
                        Button txtValue = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Width = 100 };
                        if (titles[i].Contains("扣分步骤"))
                            txtValue.Content = propertys[i];
                        else
                            txtValue.SetBinding(Button.ContentProperty, new Binding(propertys[i]));
                        txtValue.Tag = titles[i] + question.ID + "：" + question.StopsRunningTrain;
                        txtValue.Click += TxtValue_Click;
                        sp.Children.Add(txtValue);
                    }
                   
                }
                else
                {
                    if (titles[i].Contains("客流"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 50, TextAlignment = TextAlignment.Center }; ;
                        txtValue.Text = "15.00";
                        sp.Children.Add(txtValue);
                    }
                    if (titles[i].Contains("    "))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 50, TextAlignment = TextAlignment.Center }; ;
                        sp.Children.Add(txtValue);
                    }
                    else if (titles[i].Contains("试卷总分"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 100, TextAlignment = TextAlignment.Center };
                        txtValue.Text = propertys[i].ToString();
                        sp.Children.Add(txtValue);
                    }
                    else if (titles[i].Contains("场景总计时"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 120, TextAlignment = TextAlignment.Center };
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding(propertys[i]));
                        txtValue.Visibility = Visibility.Hidden;
                        TextBlock txtValue1 = new TextBlock() { FontSize = 15, Foreground = Brushes.Red, Width = 250, TextAlignment = TextAlignment.Center, Margin = new Thickness(-180, 0, 0, 0), TextWrapping = TextWrapping.Wrap };
                        txtValue1.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.PreTime"));
                        sp.Children.Add(txtValue);
                        sp.Children.Add(txtValue1);

                    }
                    else
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 120, TextAlignment = TextAlignment.Center };
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding(propertys[i]));
                        sp.Children.Add(txtValue);
                    }
                    
                }
            }
                sp.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
                sp.SetValue(Grid.ColumnProperty, colIndex);
                sp.SetValue(Grid.ColumnSpanProperty, mainlayOut.ColumnDefinitions.Count - colIndex);
                layOut.Children.Add(sp);
            
        }

        private void CreateStackPanelArea1(ExamresultsTestQuestionModel question, string[] titles, string[] propertys, int colIndex, Grid layOut)
        {
            StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(20, 0, 0, 0) };
            for (int i = 0; i < titles.Length; i++)
            {
                TextBlock txtTitle = new TextBlock() { Width = 135, Text = titles[i], Margin = new Thickness(10, 0, 10, 0) };
                sp.Children.Add(txtTitle);
                //修改成绩汇总显示 add by ljz 2023.7.25
                if (new string[] { "晚点扣分", "停运扣分", "迫停扣分", "提交元素扣分", "操作得分", "扣分步骤" }.Contains(titles[i].TrimEnd('：')))
                {
                    if (titles[i].Contains("    "))
                    {
                        Button txtValue = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Width = 100 };
                        txtValue.Content = "";
                    }
                    else
                    {
                        Button txtValue = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Width = 100 };
                        if (titles[i].Contains("扣分步骤"))
                            txtValue.Content = propertys[i];
                        else
                            txtValue.SetBinding(Button.ContentProperty, new Binding(propertys[i]));
                        txtValue.Tag = titles[i] + question.ID + "：" + question.StopsRunningTrain;
                        txtValue.Click += TxtValue_Click;
                        sp.Children.Add(txtValue);
                    }

                }
                else
                {
                    if (titles[i].Contains("    "))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 50, TextAlignment = TextAlignment.Center }; ;
                        sp.Children.Add(txtValue);
                    }
                  
                    else if (titles[i].Contains("场景总计时"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 120, TextAlignment = TextAlignment.Center};
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding(propertys[i]));
                        txtValue.Visibility = Visibility.Hidden;
                        TextBlock txtValue1 = new TextBlock() { FontSize=15,Foreground = Brushes.Red, Width = 250, TextAlignment = TextAlignment.Center, Margin = new Thickness ( -180,0,0,0), TextWrapping = TextWrapping.Wrap };
                        txtValue1.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.TestTime"));
                        sp.Children.Add(txtValue);
                        sp.Children.Add(txtValue1);
                        
                    }
                    else if (titles[i].Contains("试卷总分"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 100, TextAlignment = TextAlignment.Center };
                        txtValue.Text = propertys[i].ToString();
                        sp.Children.Add(txtValue);
                    }
                    else
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 120, TextAlignment = TextAlignment.Center };
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding(propertys[i]));
                        sp.Children.Add(txtValue);
                    }

                }
            }
            sp.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            sp.SetValue(Grid.ColumnProperty, colIndex);
            sp.SetValue(Grid.ColumnSpanProperty, mainlayOut.ColumnDefinitions.Count - colIndex);
            layOut.Children.Add(sp);

        }

        private void CreateStackPanelArea2(ExamresultsTestQuestionModel question, string[] titles, string[] propertys, int colIndex, Grid layOut)
        {
            StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(20, 0, 0, 0) };
            for (int i = 0; i < titles.Length; i++)
            {
                TextBlock txtTitle = new TextBlock() { Width = 135, Text = titles[i], Margin = new Thickness(10, 0, 10, 0) };
                sp.Children.Add(txtTitle);
                //修改成绩汇总显示 add by ljz 2023.7.25
                if (new string[] { "晚点扣分", "停运扣分", "迫停扣分", "提交元素扣分", "操作得分", "客流扣分" }.Contains(titles[i].TrimEnd('：')))
                {
                    if (titles[i].Contains("    "))
                    {
                        Button txtValue = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Width = 100 };
                        txtValue.Content = "";
                    }
                    else
                    {
                        Button txtValue = new Button() { Style = this.FindResource("LinkButton") as System.Windows.Style, Width = 100 };
                        if (titles[i].Contains("客流扣分"))
                            txtValue.Content = propertys[i];
                        else
                            txtValue.SetBinding(Button.ContentProperty, new Binding(propertys[i]));
                        txtValue.Tag = titles[i] + question.ID + "：" + question.StopsRunningTrain;
                        txtValue.Click += TxtValue_Click;
                        sp.Children.Add(txtValue);
                    }

                }
                else
                {
                    if (titles[i].Contains("    "))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 50, TextAlignment = TextAlignment.Center }; ;
                        sp.Children.Add(txtValue);
                    }
                    else if (titles[i].Contains("试卷总分"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 100, TextAlignment = TextAlignment.Center };
                        txtValue.Text = propertys[i].ToString();
                        sp.Children.Add(txtValue);
                    }
                    else if (titles[i].Contains("场景总计时"))
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 120, TextAlignment = TextAlignment.Center };
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding(propertys[i]));
                        txtValue.Visibility = Visibility.Hidden;
                        TextBlock txtValue1 = new TextBlock() { FontSize = 15, Foreground = Brushes.Red, Width = 250, TextAlignment = TextAlignment.Center, Margin = new Thickness(-180, 0, 0, 0), TextWrapping = TextWrapping.Wrap };
                        txtValue1.SetBinding(TextBlock.TextProperty, new Binding("ExamResultsModel.TestTime"));
                        sp.Children.Add(txtValue);
                        sp.Children.Add(txtValue1);

                    }
                    else
                    {
                        TextBlock txtValue = new TextBlock() { Foreground = Brushes.Red, Width = 120, TextAlignment = TextAlignment.Center };
                        txtValue.SetBinding(TextBlock.TextProperty, new Binding(propertys[i]));
                        sp.Children.Add(txtValue);
                    }
                  

                }
            }
            sp.SetValue(Grid.RowProperty, layOut.RowDefinitions.Count - 1);
            sp.SetValue(Grid.ColumnProperty, colIndex);
            sp.SetValue(Grid.ColumnSpanProperty, mainlayOut.ColumnDefinitions.Count - colIndex);
            layOut.Children.Add(sp);

        }
        private void TxtValue_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            string arg = btn.Tag.ToString();
            List<ExamresultsTestQuestionTaskStepModel> steps = null;
            if (arg.Contains("扣分步骤"))
            {
                var question = this.ExamResultsModel.ExamresultsTestQuestions.FirstOrDefault(p => p.ID == int.Parse(arg.Split('：')[1]));
                steps = new List<ExamresultsTestQuestionTaskStepModel>();
                question.ExamresultsTestQuestionTasks.ToList().ForEach(p => steps.AddRange(p.ExamresultsTestQuestionTaskStepModels.ToList().FindAll(x => x.TaskType == (int)TaskType.任务 && x.Score != x.OperationScore)));
            }
            else if (arg.Contains("客流扣分"))
            {

            }
            WinTrainLate win = new WinTrainLate(arg, steps);
            win.Owner = MainWindowNew.GetWindow(this);
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            win.ShowDialog();
        }

        public void SelectExamResults()
        {
            this.ExamResultsModel = ExamResultsDAL.GetExamResultById(int.Parse((this.Tag as object[])[0].ToString()));
            //this.ExamResultsModel.ExamresultsTestQuestions.ToList().ForEach(p => p.ExamresultsTestQuestionTasks.ToList().ForEach(x => x.Status = "已执行"));
            this.titleExamResultsModel = this.ExamResultsModel;//考试成绩查询可以查看分页 add by ljz
            this.UpdateLayOut(mainlayOut, true);
            this.UpdateLayOut(fmainlayOut, false);//modify by gy
        }

        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            var taskList = new List<ExamresultsTestQuestionTaskModel>();
            this.ExamResultsModel.ExamresultsTestQuestions.ToList().ForEach(p => taskList.AddRange(p.ExamresultsTestQuestionTasks));
            //if (ExamresultsTestQuestionTaskDAL.UpdateExamresultsTestQuestionTasks(taskList))
            //    AccountServiceHelper.Instance.ModifySubjectiveScore(this.ExamResultsModel.ID);
        }

        private void ButtonPrintResult_Click(object sender, RoutedEventArgs e)
        {
            PrintResult(this.ExamResultsModel.ID);
        }

        private void ButtonPrintLog_Click(object sender, RoutedEventArgs e)
        {
            PrintLog(this.ExamResultsModel);
        }

        public void PrintResult(int ID)
        {
            DataSet ds = ExamResultsDAL.GetExamResult(ID);
            Dictionary<string, object> Parameter = new Dictionary<string, object>
            {
                { "UserName", ds.Tables[0].Rows[0]["usernumber"].ToString() }
            };
            string file = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Report\\ExamResultNew.frx");
            //PreView pre = new PreView(ds, file, Parameter);
            //pre.ShowDialog();
        }

        private List<DataRow> MergeRows = new List<DataRow>();
        private bool HaveSpace;
        public void PrintLog(ExamResultsModel examResultsModel)
        {
            string file = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Report\\ExamResultLog.frx");
            var user = UserInfoDAL.SelectUserInfo(examResultsModel.UserID);
            Dictionary<string, object> Parameter = new Dictionary<string, object>
            {
                { "UserName", user != null ? user.UserNumber : "默认用户" },
                { "TestPaper", string.IsNullOrWhiteSpace(examResultsModel.Describe) ? "默认试卷": examResultsModel.Describe }
            };
            //DataSet ds = ExamResultsLogDAL.GetLogs(examResultsModel.ID);
            //if (ds != null && ds.Tables.Count > 0)
            //{
            //    this.MergeRows = new List<DataRow>();
            //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //    {
            //        DataRow dr = ds.Tables[0].Rows[i];
            //        if (this.MergeRows.Count > 0 && ((!string.IsNullOrWhiteSpace(this.MergeRows[this.MergeRows.Count() - 1]["Tooltips"].ToString()) && dr["Tooltips"].ToString() != this.MergeRows[this.MergeRows.Count() - 1]["Tooltips"].ToString())
            //            || (string.IsNullOrWhiteSpace(this.MergeRows[this.MergeRows.Count() - 1]["Tooltips"].ToString()) && dr["TaskID"].ToString() != this.MergeRows[this.MergeRows.Count() - 1]["TaskID"].ToString())
            //            || dr["Tooltips"].ToString() == "无效操作"))
            //            this.LogsMerge();
            //        this.MergeRows.Add(dr);
            //        if (i == ds.Tables[0].Rows.Count - 1) this.LogsMerge();
            //        string parameter = GetParameterUnJson(dr["Parameter"].ToString());
            //        dr["Parameter"] = parameter.Length == 2 ? "" : parameter;
            //    }
            //}
            //PreView pre = new PreView(ds, file, Parameter);
            //pre.ShowDialog();
        }

        private void LogsMerge()
        {
            string sumStepScore = this.MergeRows.Sum(x => decimal.Parse(x["StepScore"] is null ? "0" : x["StepScore"].ToString())).ToString();
            this.MergeRows.ForEach(p =>
            {
                if (this.HaveSpace)
                {
                    p["Score"] += " "; p["StepScore"] = sumStepScore + ' '; p["Tooltips"] += " ";
                    p["OperationTooltips"] += " "; p["TaskDescribe"] += " ";
                }
            });
            this.HaveSpace = !this.HaveSpace;
            this.MergeRows.Clear();
        }

        private static string GetParameterJson(string jsonParameter)
        {
            var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonParameter);
            var newDic = new Dictionary<string, string>();
            if (dic != null)
            {
                foreach (var keyValue in dic)
                {
                    int devType = int.Parse(keyValue.Key.Split('|')[0]);
                    int devID = int.Parse(keyValue.Key.Split('|')[1]);
                    //if (MainWindowNew.DeviceList.ContainsKey(devType) && MainWindowNew.DeviceList[devType].Find(p => p.ID == devID) != null)
                    //    newDic.Add(MainWindowNew.DeviceList[devType].Find(p => p.ID == devID).DevName, keyValue.Value);
                }
            }
            return JsonConvert.SerializeObject(newDic);
        }

        private static string GetParameterUnJson(string jsonParameter)
        {
            var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonParameter);
            string parameter = "";
            if (dic != null)
            {
                foreach (var keyValue in dic)
                {
                    int devType = int.Parse(keyValue.Key.Split('|')[0]);
                    int devID = int.Parse(keyValue.Key.Split('|')[1]);
                    //if (MainWindowNew.DeviceList.ContainsKey(devType) && MainWindowNew.DeviceList[devType].Find(p => p.ID == devID) != null)
                    //    parameter = MainWindowNew.DeviceList[devType].Find(p => p.ID == devID).DevName + ";";
                }
            }
            return parameter.TrimEnd(';');
        }

        public void UserExit()
        {
            this.UpdateExamState(false);
            this.spButton.Visibility = Visibility.Collapsed;
        }

        private void ButtonReturn_Click(object sender, RoutedEventArgs e)
        {
            MainWindowNew.CurMainWindow.toolCompetitionHis.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, MainWindowNew.CurMainWindow.toolCompetitionHis));
            MainWindowNew.CurMainWindow.toolCompetitionHis.IsSelected = true;
        }

        public void SceneDeductPoints()
        {
            new SceneDeductPoints(this.ExamResultsModel.ExamresultsTestQuestions).ShowDialog();
        }

        private void ButtonEventLog_Click(object sender, RoutedEventArgs e)
        {
            EventLog eventLog = new EventLog(this.ExamResultsModel.ID, this.HisMode);
            eventLog.Show();
        }

        private void Score_Click(object sender, RoutedEventArgs e)
        {

            string json = JsonConvert.SerializeObject(practiceScore);
            var request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ScoreService"]);
            var data = Encoding.UTF8.GetBytes(json);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var obj = JsonConvert.DeserializeObject<ScoreResult>(responseString);
            MessageBox.Show(obj.message, "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        //滚动条跟踪目标控件位置 Add by gy
        private void ScrolltoTarget(TextBlock Targetblock, ScrollViewer TargetViewer)
        {
            if (Targetblock == null || TargetViewer == null)
            {
                throw new ArgumentNullException($"{TargetViewer} or {Targetblock} cannot be null");
            }
            var currentScrollPosition = TargetViewer.VerticalOffset;
            var point = new Point(0, currentScrollPosition);
            //计算相对位置并滚动
            var targetPosition = Targetblock.TransformToVisual(TargetViewer).Transform(point);
            TargetViewer.ScrollToVerticalOffset(targetPosition.Y - 5);
        }

        private void ButtonOpenSum_Click(object sender, RoutedEventArgs e)
        {
            ButtonOpenSum.Visibility = Visibility.Collapsed;
            ButtonCloseSum.Visibility = Visibility.Visible;
        }

        private void ButtonCloseSum_Click(object sender, RoutedEventArgs e)
        {
            ButtonCloseSum.Visibility = Visibility.Collapsed;
            ButtonOpenSum.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 成绩分析 add by zzg
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Analysis_Click(object sender, RoutedEventArgs e)
        {
            string name = ExamResultsModel.m_ExamresultsTestQuestions.Where(T => T.ID == ExamResultsModel.ID).FirstOrDefault().Name;
            SequenceDiagramView sequenceDiagram = new SequenceDiagramView(ExamResultsModel.ID, name);
            sequenceDiagram.Owner = MainWindowNew.GetWindow(this);
            sequenceDiagram.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            sequenceDiagram.ShowDialog();
        }
        /// <summary>
        /// 更改试卷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TitleCom_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
            
        }

        private void TitleCom_DropDownClosed(object sender, EventArgs e)
        {
            if (ExamResultsModel != null)
            {
                this.Dispatcher.Invoke(new Action(() => { 
                    this.ClearLayOut(mainlayOut);
                    this.ClearLayOut(fmainlayOut);
                   // this.ClearLayOut(SumGrid);
                }));
                this.Dispatcher.Invoke(new Action(() =>
                {
                    //重新加载试卷 modify by gy
                    this.UpdateLayOut(mainlayOut, true);
                    this.UpdateLayOut(fmainlayOut, false);
                }));
            }
        }
    }
    public class DecimalToCheckedConverter : IValueConverter
    {
        public bool RightMode { get; set; }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return this.RightMode && (decimal)value == 10 || !this.RightMode && (decimal)value < 10;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (this.RightMode && (bool?)value == true)
                return 10;
            if (!this.RightMode && (bool?)value == true)
                return 0;
            return -1;
        }
    }
    public class ColorToCheckedConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool?)value == true ? Brushes.Red : Brushes.Black;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    public class ExecStateToVisibleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (int)value == 3 ? Visibility.Visible : Visibility.Hidden;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class StatusVisibleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString() == "已执行" ? Visibility.Hidden : Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class TextToHightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new GridLength(string.IsNullOrWhiteSpace(value == null ? "" : value.ToString()) ? 0 : 35, GridUnitType.Pixel);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class IDToVisibleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ExamResultsModel examResults = value as ExamResultsModel;
            return examResults != null && examResults.ID > 0 ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    //控件遍历 Add by gy
    public static class FindChirldHelper
    {
        public static List<T> FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            try
            {
                List<T> TList = new List<T> { };
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                    if (child != null && child is T)
                    {
                        TList.Add((T)child);
                        List<T> childOfChildren = FindVisualChild<T>(child);
                        if (childOfChildren != null)
                        {
                            TList.AddRange(childOfChildren);
                        }
                    }
                    else
                    {
                        List<T> childOfChildren = FindVisualChild<T>(child);
                        if (childOfChildren != null)
                        {
                            TList.AddRange(childOfChildren);
                        }
                    }
                }
                return TList;
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return null;
            }
        }
    }
    //执行步骤变化监听类 Add by gy
    public class ListenToStepChange
    {
        private int stepIndex;
        public TextBlock Targettbk { get; set; }
        public ScrollViewer TargetViewer { get; set; }
        public int StepIndex
        {
            get { return stepIndex; }
            set
            {
                if (value != stepIndex)
                {
                    stepIndexChange();
                }
                stepIndex = value;
            }
        }
        public delegate void stepChanged(TextBlock tbk, ScrollViewer viewer);
        public event stepChanged OnStepChanged;
        //事件触发
        private void stepIndexChange()
        {
            if (OnStepChanged != null)
            {
                OnStepChanged(Targettbk, TargetViewer);
            }
        }
    }



}
